<?php


namespace app\merchant\system\controller;

use app\common\model\Merchant;
use app\common\model\SysMerchantAdmin;
use app\merchant\system\service\MerAdminService;
use app\merchant\system\validate\MerAdminLoginValidate;
use app\merchant\system\validate\MerAdminTenantByUsernameValidate;
use common\event\EventConst;
use support\exception\BadException;
use support\utils\RandomUtil;
use support\utils\Time;
use support\utils\UserUtil;
use think\facade\Db;
use Webman\Event\Event;

class LoginController extends BaseController
{
    protected array $noNeedLogin = [
        'login',
        'tenantByUsername',
    ];

    public function login()
    {
        MerAdminLoginValidate::goCheck(input());

        $username = input('username');
        $password = input('password');
        $tenant_id = input('tenant_id');

        $tenant = Merchant::where("tenant_id", '=', $tenant_id)
            ->where('expire_time', ">", Time::now())
            ->field([
                'expire_time',
                'status',
            ])
            ->find();
        if (!$tenant) {
            throw new BadException("租户已经过期不可登录该租户,请先续费");
        }
        if ($tenant['status'] != 0) {
            throw new BadException("租户状态异常,请联系管理员");
        }


        $user = SysMerchantAdmin::where([
            'username' => $username,
            'tenant_id' => $tenant_id,
        ])->field(['id', 'password', 'salt', "status"])->find();
        if (!$user) {
            throw new BadException("账号密码错误");
        }

        if ($user['status'] != 0) {
            throw new BadException("账号已经被禁用");
        }

        if (!MerAdminService::checkPassword($password, $user['password'], $user['salt'])) {
            throw new BadException("账号密码错误");
        }

        $token = md5($username . $password . RandomUtil::randomStr());
        $user->token = $token;
        $user->ip = request()->getRealIp();
        $user->login_time = Time::now();
        $user->save();
        Event::emit(EventConst::USER_LOGIN, [
            'uid' => $user['id'],
            'token' => $token,
            'username' => $username,
            'ip' => $user->ip,
            'time' => $user->login_time,
            'os' => request()->os,
            'tenant_id' => $tenant_id,
        ]);

        return $this->success([
            "tokenName" => "Authorization",
            'tokenValue' => $token
        ]);
    }

    public function tenantByUsername()
    {
        //根据username找到是否有多个租户 如果多租户的时候用户必须得选择一个租户登录
        MerAdminTenantByUsernameValidate::goCheck(input());
        $username = input('username');
        $ids = SysMerchantAdmin::where([
            'username' => $username,
        ])->column('tenant_id');
        if (!$ids) {
            return $this->success();
        }
        $data = Merchant::where("tenant_id", 'in', $ids)
//            ->where('expire_time', ">", Time::now())
            ->field([
                'tenant_id as value',
                'name as label',
            ])->select();
        return $this->success($data);
    }

    public function loginOut()
    {
        Db::table(SysMerchantAdmin::getTable())->where([
            "id" => UserUtil::getUid()
        ])->update([
            "token" => ""
        ]);
        return $this->success();
    }

}